package com.zqr.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.List;

/**
 * 消费者
 */
@Slf4j
public class ThreadConsumer implements Runnable{
    private List<String> container;
    private long million; //睡眠时间

    public ThreadConsumer(List<String> container, long million) {
        this.container = container;
        this.million = million;
    }

    public void consume(){
        int i = 0;
        while(true){
            if (container.size() == 0){
                //停止消费
                try {
                    synchronized (container){
                        log.info("容器中没有数据，{} thread waiting ...", Thread.currentThread().getName());
                        container.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            try {
                Thread.sleep(million);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //消费数据
/*            Iterator<String> iterator = container.iterator();
            if (iterator.hasNext()){
                //TODO 该模型的问题主要在于ArrayList的删除元素操作报错，导致线程挂了
                iterator.remove();
                log.info("消费者消费数据, 消费后的container current size:{}", container.size());
            }*/
            //用下面这个不会报错，能够实现基本的效果。但是下面这个方式删除集合里的数据好像是潜在问题的
            container.remove(0);
            log.info("消费者消费数据, 消费后的container current size:{}", container.size());
            synchronized (container){
                log.info("消费者消费数据后，唤醒生产者，{} thread use notifyAll ..", Thread.currentThread().getName());
                container.notifyAll();
            }
        }
    }

    @Override
    public void run() {
        consume();
    }
}
